﻿// Fill out your copyright notice in the Description page of Project Settings.


#include "Trigger.h"

#include "Components/BoxComponent.h"
#include "Components/SphereComponent.h"
#include "Inrerface/TakeInterface.h"

ATrigger::ATrigger()
{
	PrimaryActorTick.bCanEverTick = false;
	RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("Scene"));
	Box = CreateDefaultSubobject<UBoxComponent>(TEXT("Box"));
	Box->SetupAttachment(RootComponent);
	Sphere = CreateDefaultSubobject<USphereComponent>(TEXT("Sphere"));
	Sphere->SetupAttachment(RootComponent);
	Box->SetCollisionEnabled(ECollisionEnabled::NoCollision);
	Sphere->SetCollisionEnabled(ECollisionEnabled::NoCollision);
}

void ATrigger::BeginPlay()
{
	Super::BeginPlay();
	TriggerInit();
}

void ATrigger::OnConstruction(const FTransform& Transform)
{
	Super::OnConstruction(Transform);
	switch (PlantCollision)
	{
	case EPlantCollision::EPC_Box:
		Box->SetVisibility(true);
		Sphere->SetVisibility(false);
		Box->SetBoxExtent(BoxSize);
		break;
	case EPlantCollision::EPC_Sphere:
		Box->SetVisibility(false);
		Sphere->SetVisibility(true);
		Sphere->SetSphereRadius(SphereSize);
		break;
	}
}

void ATrigger::TriggerInit()
{
	switch (PlantCollision)
	{
	case EPlantCollision::EPC_Box:
		OverlapBind(Box);
		break;
	case EPlantCollision::EPC_Sphere:
		OverlapBind(Sphere);
		break;
	}
}

void ATrigger::OverlapBind(const TObjectPtr<UPrimitiveComponent> PrimitiveComponent)
{
	PrimitiveComponent->SetCollisionEnabled(ECollisionEnabled::QueryOnly);
	PrimitiveComponent->SetCollisionObjectType(ECollisionChannel::ECC_WorldDynamic);
	PrimitiveComponent->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Overlap);
	// 设置可以触发重叠事件
	PrimitiveComponent->BodyInstance.bGenerateWakeEvents = true;
	PrimitiveComponent->SetUseCCD(true);
	PrimitiveComponent->OnComponentBeginOverlap.AddDynamic(this, &ThisClass::OverlapCollision);
}

void ATrigger::OverlapCollision(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	if (ITakeInterface* TakeInterface = Cast<ITakeInterface>(OtherActor))
	{
		switch (TriggeredState)
		{
		case ETriggeredState::ETS_Germinate:
			TakeInterface->TriggerOverlapGrowth();
			break;
		case ETriggeredState::ETS_Withered:
			TakeInterface->TriggerOverlapWithered();
			break;
		case ETriggeredState::ETS_Revitalize:
			TakeInterface->TriggerOverlapRevitalize();
			break;
		}
	}
}
